<template>
  <view class="container">
    <uni-forms ref="form" :rules="{}">
      <uni-forms-item label="用户名" name="">
        <uni-easyinput v-model="user.name" @change="usernameChange" placeholder="请输入姓名" />
      </uni-forms-item>
      <uni-forms-item label="密码" name="">
        <uni-easyinput v-model="user.password" placeholder="请输入密码" type="password"/>
      </uni-forms-item>
      <uni-forms-item label="电话" name="">
        <uni-easyinput v-model="user.telephone" placeholder="请输入你的电话号码" />
      </uni-forms-item>
      <uni-forms-item label="邮箱" name="">
        <uni-easyinput v-model="user.email" placeholder="请输入邮箱" />
      </uni-forms-item>
    </uni-forms>
    <uni-button type="primary" @click="register">注册</uni-button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      user: {
        id: 0,
        name: "",
        password: '',
        telephone: '',
        email: ''
      },
      isPhoneValid: true,
      isEmailValid: true
    };
  },
  methods: {
    usernameChange(e) {
      console.log(e.detail.value); // 获取输入的值
    },
    validatePhone(phone) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      return phoneRegex.test(phone);
    },
    validateEmail(email) {
      const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
      return emailRegex.test(email);
    },
    register() {
      if (!this.isPhoneValid || !this.isEmailValid) {
        uni.showToast({
          title: '请检查电话号码和邮箱格式',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      const data = JSON.stringify(this.user);
      uni.request({
        url: 'http://localhost:8090/freshmenapp/user/register',
        method: 'POST',
        data: data,
        header: {
          'content-type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({
              title: '注册成功',
              icon: 'success',
              duration: 2000
            });
            uni.redirectTo({
              url: '/pages/my/login'
            });
          } else {
            uni.showToast({
              title: '失败',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '请求失败',
            icon: 'none',
            duration: 2000
          });
          console.error('请求失败:', err);
        }
      });
    }
  },
  onShow() {
    uni.onTabBarMidButtonTap(function (e) {
      console.log(e);
    });
  },
  watch: {
    'user.telephone'(newVal) {
      this.isPhoneValid = this.validatePhone(newVal);
    },
    'user.email'(newVal) {
      this.isEmailValid = this.validateEmail(newVal);
    }
  }
}
</script>

<style>
  .container {
    padding: 20px;
    font-size: 14px;
    line-height: 24px;
  }
</style>